/**
* @CopyRight tstudy.com.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.active;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;

import com.loopj.android.http.ResponseHandlerInterface;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.base.WebViewFragment;
import com.tstudy.laoshibang.custom.BorderTextView;
import com.tstudy.laoshibang.custom.CustomTextView;
import com.tstudy.laoshibang.event.ActiveLoveEvent;
import com.tstudy.laoshibang.event.ActiveViewEvent;
import com.tstudy.laoshibang.login.LoginActivity;
import com.tstudy.laoshibang.mode.Active;
import com.tstudy.laoshibang.mode.response.ActiveDetailResponse;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;

import android.annotation.SuppressLint;
import android.app.Application;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebSettings.PluginState;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.greenrobot.event.EventBus;
@SuppressLint("InflateParams")
@EFragment(R.layout.active_detail)
public class ActiveDetailFragment extends BaseFragment{
	final static String TAG = "active_detail";
	public ActiveDetailFragment() {
		super();
	}
	
	@ViewById(R.id.active_detail_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.active_detail_progress)
	RelativeLayout mProgressLayout;
//	@ViewById(R.id.active_detail_viewpage_layout)
//	LinearLayout mViewPagerSelectLayout;
	@ViewById(R.id.active_detail_viewpage)
	ViewPager mViewPager;
	
	@ViewById(R.id.active_detail_active_time)
	TextView mActiveTime;
	
	@ViewById(R.id.active_detail_active_creator)
	TextView mActiveCreator;
	
	@ViewById(R.id.active_detail_active_address)
	TextView mActiveAddress;
	
	@ViewById(R.id.active_detail_active_apply_time)
	TextView mApplyTime;
	@ViewById(R.id.active_detail_active_apply_time_sp)
	View mApplyTimeSp;
	
	
	@ViewById(R.id.active_detail_active_apply_type)
	TextView mActiveType;
	@ViewById(R.id.active_detail_active_apply_type_sp)
	View mActiveTypeSp;
	
	@ViewById(R.id.active_detail_active_contact)
	TextView mActiveContact;
	@ViewById(R.id.active_detail_active_contact_sp)
	BorderTextView mActiveContactSp;
	
	@ViewById(R.id.active_detail_info)
	WebView mWebView;
	
	@ViewById(R.id.active_detail_category_layout)
	RelativeLayout mActiveCategoryLayout;
	
	@ViewById(R.id.active_detail_love_action)
	ImageView mLoveAction;
	
	@ViewById(R.id.active_detail_love_icon)
	ImageView mLoveIcon;
	
	@ViewById(R.id.active_detail_love_count)
	TextView mLoveCount;
	
	@ViewById(R.id.active_detail_view_count)
	TextView mViewCount;
	
	@ViewById(R.id.active_detail_apply)
	TextView mActiveApply;
	
	@ColorRes(R.color.theme_dark_blue)
	int mLinkColor;
	
	ListItemPageAdapter mPageAdapter;
	
	boolean mIsFirstLoad = true;
	Handler mHandler;
	LayoutInflater mInflater;
	
	public static final int BANNER_DURATION = 3000;
	int mCurrentPosition = 0;
	List<View> mViewList = new ArrayList<View>();
	List<Active> mActives = new ArrayList<Active>();
	@StringRes(R.string.select_all)
	String mSelectAllStr;
	int mSelectAllKey = -1;
	int mActiveId;
	int mPosition;
	Active mActive;
	int redTextColor = BaseApplication.getResColor(R.color.theme_red);
	int grayTextColor = BaseApplication.getResColor(R.color.text_color_gray);
	String mGroupId;

	public static void add(int containerViewId,int actId,int position) {
		add(containerViewId, actId, position,null);
	}
	public static void add(int containerViewId,int actId,int position,String groupId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		args.putInt(CONSTANT.ARGS.ACTIVE_ID, actId);
		args.putInt(CONSTANT.ARGS.POSITION, position);
		args.putString(CONSTANT.ARGS.GROUP_ID, groupId);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,ActiveDetailFragment_.class.getName(),args);
		((BaseActivity) BaseApplication.mCurrentActivity).add(containerViewId, fragment, TAG);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		super.onCreate(savedInstanceState);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			initWebView();
			mViewPager.getLayoutParams().height = BaseApplication.mScreenWidth/2;
			mRootLayout.setOnClickListener(null);
			mPageAdapter = new ListItemPageAdapter();
			mViewPager.setAdapter(mPageAdapter);
			mViewPager.setOnPageChangeListener(mPageAdapter);
//			mViewList.clear();
//			for (int i = 0; i < 4; i++) {
//				ImageView banner = new ImageView(BaseApplication.mContext);
//				banner.setScaleType(ScaleType.FIT_XY);
////				banner.setImageResource(R.drawable.banner01);
////				HttpManager.getInstance().loadBrowseImage(banner, item.pic);
//				mViewList.add(banner);
//				fillSelectLayout(mViewPagerSelectLayout, i);
//			}
//			mPageAdapter.setData(mViewList);
//			addCallBacks();
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					getActiveDetail();
					viewAction(mActiveId, CONSTANT.ASSO_TYPE_ACTIVE);
				}
			}, CONSTANT.LOAD_DATA_DELAY_TIME);
		}
	}
	
	@SuppressLint("SetJavaScriptEnabled")
	@SuppressWarnings("deprecation")
	private void initWebView() {// 初始化
		mWebView.getSettings().setSupportZoom(false); // Zoom Control on web (You
		// don't need this
		mWebView.getSettings().setJavaScriptEnabled(true);// 可用JS
		mWebView.getSettings().setAllowContentAccess(true);
		mWebView.getSettings().setPluginState(PluginState.ON);
		mWebView.getSettings().setBuiltInZoomControls(true);
		mWebView.getSettings().setLoadsImagesAutomatically(true);
		mWebView.getSettings().setAllowFileAccess(true);
		mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
		// mWebView.getSettings()
		// .setUserAgentString(
		// "Mozilla/5.0 (Linux; U; Android 2.2.1; zh-cn; MB525 Build/3.4.2-117) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");
		mWebView.setScrollBarStyle(0);// 滚动条风格，为0就是不给滚动条留空间，滚动条覆盖在网页上
		mWebView.getSettings().setLoadWithOverviewMode(true);
		// sdk 11以上
		// mWebView.getSettings().setDisplayZoomControls(true);
		mWebView.getSettings().setUseWideViewPort(true);
		mWebView.getSettings().setDatabaseEnabled(true);
		mWebView.getSettings().setDomStorageEnabled(true);
		// mWebView.getSettings().setGeolocationEnabled(true);
		mWebView.getSettings().setAppCacheEnabled(true);
		mWebView.getSettings().setAppCacheMaxSize(10000);
		mWebView.setWebChromeClient(new WebChromeClient(){
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
				if (newProgress >= 100) {
				}
			}
			@Override
			public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
				return super.onJsAlert(view, url, message, result);
			}
			
		});
	}
	
	public void setView(){
		if (mActive != null) {
			mActiveTime.setText(mActive.actTime);
			mActiveCreator.setText(mActive.unit.name);
			mActiveAddress.setText(mActive.unit.address);
			mActiveAddress.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					ActiveMapFragment.add(mFragmentId, mActive.unit.latitude,mActive.unit.longitude);
				}
			});
			
			if (!TextUtils.isEmpty(mActive.bmUrl)) {
				mActiveType.setMovementMethod(LinkMovementMethod.getInstance());
				String desc = mActiveType.getText() + mActive.bmUrl;
				mActiveType.setText(spannableDesc(FeedCellType.FeedCell_type_url, desc, mActive.bmUrl));
				mActiveType.setVisibility(View.VISIBLE);
				mActiveTypeSp.setVisibility(View.VISIBLE);
			}else{
				mActiveType.setVisibility(View.GONE);
				mActiveTypeSp.setVisibility(View.GONE);
			}
			if (!TextUtils.isEmpty(mActive.bmTime)) {
				mApplyTime.setText(mApplyTime.getText() + mActive.bmTime);
				mApplyTime.setVisibility(View.VISIBLE);
				mApplyTimeSp.setVisibility(View.VISIBLE);
			}else{
				mApplyTime.setVisibility(View.GONE);
				mApplyTimeSp.setVisibility(View.GONE);
			}
			if (!TextUtils.isEmpty(mActive.linkPhone)) {
				mActiveContact.setMovementMethod(LinkMovementMethod.getInstance());
				String desc = mActiveContact.getText() + mActive.linkPerson + " " + mActive.linkPhone;
				mActiveContact.setText(spannableDesc(FeedCellType.FeedCell_type_phone, desc, mActive.linkPhone));
				mActiveContact.setVisibility(View.VISIBLE);
				mActiveContactSp.setVisibility(View.VISIBLE);
			}else{
				mActiveContact.setVisibility(View.GONE);
				mActiveContactSp.setVisibility(View.GONE);
			}
			mWebView.loadData(mActive.detail,CONSTANT.MIME_TYPE, null);
			if (!TextUtils.isEmpty(mActive.classifys)) {
				fillCagetory(mActiveCategoryLayout,mActive.classifys.split(","));
			}
			mLoveAction.setSelected(mActive.isPraise==1);
			mLoveAction.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (BaseApplication.checkLogin()) {
						v.setSelected(mActive.isPraise==0);
						CommonUtil.loveAnimator(v);
						mActive.isPraise = mActive.isPraise==1?0:1;
						mLoveIcon.setSelected(mActive.isPraise==1);
						mActive.praiseNum = mActive.isPraise==1?mActive.praiseNum+1:mActive.praiseNum-1;
						if (mActive.isPraise == CONSTANT.IS_PRISED) {
							mLoveCount.setTextColor(redTextColor);
						}else{
							mLoveCount.setTextColor(grayTextColor);
						}
						mLoveCount.setText(mActive.praiseNum+"");
						loveAction(mActive.actId,CONSTANT.ASSO_TYPE_ACTIVE,mActive.isPraise==1?CONSTANT.LOVE_ACTION:CONSTANT.UNLOVE_ACTION);
					}else{
						LoginActivity.show();
					}
				}
			});
			mLoveIcon.setSelected(mActive.isPraise==1);
			if (mActive.isPraise == CONSTANT.IS_PRISED) {
				mLoveCount.setTextColor(redTextColor);
			}else{
				mLoveCount.setTextColor(grayTextColor);
			}
			mLoveCount.setText(mActive.praiseNum + "");
			String viewCountStr = BaseApplication.mContext.getString(R.string.active_detail_view_count);
			mViewCount.setText(String.format(viewCountStr, mActive.accessNum));
			fillPager();
			switch (mActive.isBaoming) {
			case CONSTANT.BAOMING_STATUS_DISABLE:
				mActiveApply.setVisibility(View.GONE);
				break;
			case CONSTANT.BAOMING_STATUS_ENABLE:
				mActiveApply.setVisibility(View.VISIBLE);
				mActiveApply.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						ApplyFragment.add(mFragmentId,mActive);
					}
				});
				break;
			case CONSTANT.BAOMING_STATUS_HAS:
				mActiveApply.setVisibility(View.VISIBLE);
				mActiveApply.setText(R.string.active_baoming_has);
				mActiveApply.setBackgroundResource(R.drawable.red_corner_view_disable);
				break;
			case CONSTANT.BAOMING_STATUS_OVER:
				mActiveApply.setVisibility(View.VISIBLE);
				mActiveApply.setText(R.string.active_baoming_over);
				mActiveApply.setBackgroundResource(R.drawable.red_corner_view_disable);
				break;
			default:
				break;
			}
//			if (mActive.isBaoming == CONSTANT.BAOMING_STATUS_ENABLE) {
//				mActiveApply.setVisibility(View.VISIBLE);
//				mActiveApply.setOnClickListener(new OnClickListener() {
//					@Override
//					public void onClick(View v) {
//						ApplyFragment.add(mFragmentId,mActive);
//					}
//				});
//			}else{
//				
//			}
		}
	}
	
	public void fillPager(){
		mViewList.clear();
		String [] imgs = mActive.imgIdxNames.split(",");
		int size = imgs.length;
		if (size > 0) {
			mViewPager.setVisibility(View.VISIBLE);
		}
		for (int i = 0; i < size; i++) {
			RelativeLayout layout = (RelativeLayout) mInflater.inflate(R.layout.active_detail_header_pager, null);
			ImageView img = (ImageView) layout.findViewById(R.id.active_detail_header_pager_img);
			TextView title = (TextView) layout.findViewById(R.id.active_detail_header_pager_title);
			ImageView shadow = (ImageView) layout.findViewById(R.id.active_detail_header_pager_shadow);
			shadow.setVisibility(View.VISIBLE);
			HttpManager.getInstance().loadCommonImage(img, imgs[i] + CommonUtil.buildCropUrl(BaseApplication.mScreenWidth,BaseApplication.mScreenWidth/2));
			title.setText(mActive.title);
			mViewList.add(layout);
			ImageView leftIcon = (ImageView) layout.findViewById(R.id.active_detail_header_pager_left_icon);
			ImageView rightIcon = (ImageView) layout.findViewById(R.id.active_detail_header_pager_right_icon);
			if (i == 0) {
				if (size == 1) {
					leftIcon.setVisibility(View.GONE);
					rightIcon.setVisibility(View.GONE);
				}else{
					leftIcon.setVisibility(View.GONE);
					rightIcon.setVisibility(View.VISIBLE);
				}
			}else if(i == size -1){
				leftIcon.setVisibility(View.VISIBLE);
				rightIcon.setVisibility(View.GONE);
			}else{
				leftIcon.setVisibility(View.VISIBLE);
				rightIcon.setVisibility(View.VISIBLE);
			}
//			fillSelectLayout(mViewPagerSelectLayout, i);
		}
		mPageAdapter.setData(mViewList);
		addCallBacks();
	}
	
	int mIndexMargin = CommonUtil.dip2px(6);
	public void fillSelectLayout(LinearLayout layout,int position){
		ImageView image = new ImageView(BaseApplication.mContext);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
		lp.setMargins(mIndexMargin, 0, mIndexMargin, 0);
//		image.setImageResource(R.drawable.active_detail_pager_selector);
		if (position == 0) {
			image.setSelected(true);
		}
		layout.addView(image, lp);
	}
	
	class ListItemPageAdapter extends PagerAdapter implements OnPageChangeListener{
		List<View> mViewList = new ArrayList<View>();
		public void setData(List<View> viewList){
			mViewList = viewList;
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return mViewList.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
		
		 @Override  
		    public void destroyItem(ViewGroup container, int position,Object object) {  
		        container.removeView(mViewList.get(position));  

		    }  

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(mViewList.get(position));
			return mViewList.get(position);
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onPageSelected(int position) {
			changeSelectBg(position);
			
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			// TODO Auto-generated method stub
		}
		
	}

	public void changeSelectBg(int position){
//			if (mViewPagerSelectLayout != null) {
//				mViewPagerSelectLayout.getChildAt(position).setSelected(true);
//				mCurrentPosition = position;
//				int childCount = mViewPagerSelectLayout.getChildCount();
//				for (int i = 0; i < childCount; i++) {
//					mViewPagerSelectLayout.getChildAt(i).setSelected(i==position);
//				}
//			}
			addCallBacks();
	} 
	
	public void removeCallbacks(){
		mHandler.removeCallbacks(changeHeaderTask);
	}
	
	public void addCallBacks(){
		removeCallbacks();
		mHandler.postDelayed(changeHeaderTask, BANNER_DURATION);
	}
	Runnable changeHeaderTask = new Runnable() {
		@Override
		public void run() {
			int size = mViewList.size();
			mCurrentPosition++;
			if (mCurrentPosition == size) {
				mCurrentPosition = 0;
			}
			mViewPager.setCurrentItem(mCurrentPosition);
		}
	};
	
	/**
	 * 活动点赞
	 * @param activeId
	 * @param type
	 * @param isPraise
	 */
	private void loveAction(int activeId,int type,final int isPraise){
		BaseListJsonHandler<BaseResponse> response = new BaseListJsonHandler<BaseResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (mPosition >= 0) {
						ActiveLoveEvent event = new ActiveLoveEvent();
						event.isPrised = isPraise;
						event.position = mPosition;
						EventBus.getDefault().post(event);
					}
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					BaseResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().loveAction(BaseApplication.mUserNo, type, activeId,isPraise,mGroupId,response);
	}
	
	/**
	 * 浏览计数
	 * @param activeId
	 * @param type
	 * @param isPraise
	 */
	private void viewAction(int activeId,int type){
		ResponseHandlerInterface response = new BaseListJsonHandler<BaseResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (mPosition >= 0) {
						ActiveViewEvent event = new ActiveViewEvent();
						event.position = mPosition;
						EventBus.getDefault().post(event);
					}
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					BaseResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().viewAction(BaseApplication.mUserNo, type, activeId,mGroupId, response);
	}
	
	private void getActiveDetail(){
		if (mIsLoading) {
			return;
		}
		mIsLoading = true;
		BaseListJsonHandler<ActiveDetailResponse> response = new BaseListJsonHandler<ActiveDetailResponse>() {
			public void onStart() {
				showProgressBar(mProgressLayout);
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, ActiveDetailResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					mActive = response.getData();
					setView();
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					ActiveDetailResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected ActiveDetailResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,ActiveDetailResponse.class);
			}
		};
		HttpManager.getInstance().getActiveDetail(BaseApplication.mUserNo, mActiveId, mGroupId,response);
	}
	int mAttrItemMargin = CommonUtil.dip2px(10);
	int corlorType = 6;
	@ColorRes(R.color.blue_corner_line)
	int blueColor;
	@ColorRes(R.color.green_corner_line)
	int greenColor;
	@ColorRes(R.color.orange_corner_line)
	int orangeColor;
	@ColorRes(R.color.blue_dark_corner_line)
	int blueDarkColor;
	@ColorRes(R.color.purple_corner_line)
	int purpleColor;
	@ColorRes(R.color.red_corner_line)
	int redColor;
	
	public void fillCagetory(RelativeLayout layout,String [] names){
		layout.removeAllViews();
		int previousViewId = 0;
		int firstViewId = 0;
		int attrWidth = mAttrItemMargin;
		int size = names.length;
		for (int i = 0; i < size; i++) {
			CustomTextView textView = buildAttrTextView(names[i],i);
			switch (i%corlorType) {
			case 0:
				textView.setBackgroundResource(R.drawable.green_border_corner);
				textView.setTextColor(greenColor);
				break;
			case 1:
				textView.setBackgroundResource(R.drawable.blue_border_corner);
				textView.setTextColor(blueColor);
				break;
			case 2:
				textView.setBackgroundResource(R.drawable.orange_border_corner);
				textView.setTextColor(orangeColor);
				break;
			case 3:
				textView.setBackgroundResource(R.drawable.blue_dark_border_corner);
				textView.setTextColor(blueDarkColor);
				break;
			case 4:
				textView.setBackgroundResource(R.drawable.green_border_corner);
				textView.setTextColor(greenColor);
				break;
			case 5:
				textView.setBackgroundResource(R.drawable.red_border_corner);
				textView.setTextColor(redColor);
				break;

			default:
				break;
			}
			int viewWidth = textView.getViewWidth();
			RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
			if (i == 0) {
				attrWidth += viewWidth + mAttrItemMargin;
//				lp.addRule(RelativeLayout.BELOW,firstViewId);
				firstViewId = textView.getId();
				lp.setMargins(mAttrItemMargin, mAttrItemMargin, mAttrItemMargin, 0);
			}else if (attrWidth + viewWidth + mAttrItemMargin > BaseApplication.mScreenWidth ) {//换行
				lp.addRule(RelativeLayout.BELOW,firstViewId);
				lp.setMargins(mAttrItemMargin, 0, mAttrItemMargin, 0);
				firstViewId = textView.getId();
				attrWidth = viewWidth + mAttrItemMargin;
			}else{
				attrWidth += viewWidth + mAttrItemMargin;
				lp.addRule(RelativeLayout.RIGHT_OF,previousViewId);
				lp.addRule(RelativeLayout.ALIGN_BOTTOM,i*10);
				lp.setMargins(0, 0, mAttrItemMargin, 0);
			}
			layout.addView(textView,lp);
			previousViewId = textView.getId();
		}
	}
	
	/**
	 * 创建属性TextView
	 * @param attr  属性描述对象
	 * @param key 属性id
	 * @param value 属性值
	 * @param position 
	 * @return
	 */
	int mAttrPaddingTop = CommonUtil.dip2px(5);
	int mAttrPaddingLeft= CommonUtil.dip2px(8);
	int mAttrMinWidth = CommonUtil.dip2px(50);
	int mSelectColorIndex = 0;
	public CustomTextView buildAttrTextView(final String name,final int position){
		CustomTextView textView = new CustomTextView(BaseApplication.mContext);
		textView.setBackgroundResource(R.drawable.white_corner_view);

		textView.setCustomText(name,mAttrPaddingLeft*2);
		LogUtil.d("textView.width ==" + textView.getMeasuredWidth());
		textView.setTextSize(14);
		textView.setPadding(mAttrPaddingLeft, mAttrPaddingTop, mAttrPaddingLeft, mAttrPaddingTop);
		textView.setId((position+1)*10);
		textView.setGravity(Gravity.CENTER);
		textView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				changeAttrBg((TextView)v,dictionary,position);
			}
		});
		int minWidth = Math.max(mAttrMinWidth, textView.getViewWidth());
		textView.setWidth(minWidth);
		return textView;
	}
	
	@Click({R.id.active_detail_back,R.id.active_detail_share})
	public void actionClick(View view){
		switch (view.getId()) {
		case R.id.active_detail_back:
			backAction(mFragmentId);
			break;
		case R.id.active_detail_share:
//			showShareDialog();
			share(mActive);
			break;
		default:
			break;
		}
	}
	
	Dialog mShareDialog;
	LinearLayout mDialogView;
	public void share(Active active){
		String mDefaultShareStr = BaseApplication.getResString(R.string.community_list_title);
		String mShareImg = null;
		if (!TextUtils.isEmpty(mActive.imgIdxNames)) {
			String [] imgs = mActive.imgIdxNames.split(",");
			mShareImg = imgs[0];
		}
		if(mShareDialog == null){
			mDialogView = (LinearLayout) mInflater.inflate(R.layout.share_pop, null);
			mShareDialog = buildAlertDialog(mDialogView,CommonUtil.dip2px(20));
		}
		if (mShareDialog.isShowing()) {
			return;
		}
		final String title = TextUtils.isEmpty(active.title)?mDefaultShareStr:active.title;
		final String content = TextUtils.isEmpty(active.summary)?mDefaultShareStr:active.summary;
		CommonUtil.showShareDialog(CONSTANT.ASSO_TYPE_ACTIVE, mDialogView,mShareDialog, mInflater, mShareImg, title, content,active.shareUrl);
	}
	
	
	/**
	 * spannable 描述字符串
	 * @param desc
	 * @param action
	 * @return
	 */
	public SpannableStringBuilder spannableDesc(FeedCellType type,String desc,String spannableStr){
		SpannableStringBuilder spannable = new SpannableStringBuilder(desc);
		int start = desc.indexOf(spannableStr);
		int end = start + spannableStr.length();
		ActiveClickSpan linkClick = new ActiveClickSpan(type, spannableStr);
		spannable.setSpan(linkClick, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		return spannable;
	}
	
	public enum FeedCellType {
		FeedCell_type_phone, FeedCell_type_url
	}
	
	class ActiveClickSpan extends ClickableSpan {
		FeedCellType type;
		String content;
		public ActiveClickSpan(FeedCellType type,String content){
			this.type = type;
			this.content = content;
		}
		@Override
		public void updateDrawState(TextPaint ds) {
			ds.setColor(mLinkColor); //设置链接的文本颜色
			ds.setUnderlineText(true); //去掉下划线
		}
		@Override
		public void onClick(View widget) {
			if(type == FeedCellType.FeedCell_type_phone){
				CommonUtil.dial(content);
			}else if(type == FeedCellType.FeedCell_type_url){
				CommonUtil.openUrl(content);
				try{
					Intent intent = new Intent(Intent.ACTION_VIEW);        
					Uri content_url = Uri.parse(content);   
					intent.setData(content_url);  
					BaseApplication.mCurrentActivity.startActivity(intent);
				}catch(Exception e){
					if (content.indexOf("http://") < 0) {
						content = "http://"+content;
					}
					WebViewFragment.add(mFragmentId, content, "报名网址");
				}
			}
		}
	}

	public void afterLoading(){
		mIsLoading = false;
		hideProgressBar(mProgressLayout);
	}
	@Override
	public void clear() {
		// TODO Auto-generated method stub
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
			mActiveId = args.getInt(CONSTANT.ARGS.ACTIVE_ID);
			mPosition = args.getInt(CONSTANT.ARGS.POSITION);
			mGroupId = args.getString(CONSTANT.ARGS.GROUP_ID);
		}
	}
}
